<template>
  <div class="box">
    <div class="card-container">
      <el-row :gutter="10">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
          <el-col :span="19" :offset="0">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker v-model="queryParams.createTime" type="datetimerange" style="width:320px"
                range-separator="至" start-placeholder="开始日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="震中地名" prop="locname">
              <el-input v-model="queryParams.locname" placeholder="请输入震中地名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="信息类型" prop="msgType">
              <el-radio-group v-model="queryParams.msgType">
                <el-radio :key="'0'" :label="'0'">全部</el-radio>
                <el-radio v-for="dict in dict.type.sys_event_type" :key="dict.value"
                  :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item> -->

          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item>
              <el-button  icon="el-icon-search" size="mini" @click="handleQuery">搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['drillReport:add']"
          @click="handleAdd">新增演练</el-button>
        <el-button   icon="el-icon-delete" size="mini" v-hasPermi="['drillReport:remove']"
          :disabled="multiple" v-show="!multiple" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row> -->
    <div class="card-container">
      <div class="body-title">
        <div class="body-title-left">
          速报演练
        </div>
        <div class="body-title-right">
          <!-- <el-button   v-hasPermi="['drillReport:add']" @click="handleAdd">新增演练
          </el-button> -->
          <el-button icon="el-icon-plus" size="mini" v-hasPermi="['drillReport:add']" @click="handleAdd">新增演练</el-button>
          <el-button icon="el-icon-delete" size="mini" v-hasPermi="['drillReport:remove']" :disabled="multiple"
            v-show="!multiple" @click="handleDelete">删除</el-button>
        </div>
      </div>

      <el-table :data="tableData" height="500" :row-key="getRowKey" :row-class-name="getRowClass" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column prop="createTime" align="center" show-overflow-tooltip label="创建时间" width="240">
        </el-table-column>
        <!-- <el-table-column prop="msgType" align="center" show-overflow-tooltip label="信息类型">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_event_type" :value="scope.row.msgType" />
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="演练地震事件信息" width="300">
          <template slot-scope="scope">
            <div class="eewMessage">
              <div>
                <div style="flex: 1;">震级：</div>
                <div style="flex: 2;">{{ scope.row.magnitude || '--' }}M</div>
              </div>
              <div>
                <div style="flex: 1;">震中烈度：</div>
                <div style="flex: 2;">{{ scope.row.epiintensity || '--' }}°</div>
              </div>
              <div>
                <div style="flex: 1;">震源深度：</div>
                <div style="flex: 2;">{{ scope.row.focdepth || '--' }}km</div>
              </div>
              <div>
                <div style="flex: 1;">震中经度：</div>
                <div style="flex: 2;">{{ scope.row.epilon || '--' }}°</div>
              </div>
              <div>
                <div style="flex: 1;">震中纬度：</div>
                <div style="flex: 2;">{{ scope.row.epilat || '--' }}°</div>
              </div>
              <div>
                <div style="flex: 1;">震中地名：</div>
                <div style="flex: 2;">{{ scope.row.locname || '--' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="信息接收对象" width="350" prop="drillProjectVOS">
          <template slot-scope="scope">
            <el-tree :data="scope.row.drillProjectVOS" style="height: 205px;overflow-y: auto;"
              :props="{ label: 'name' }"></el-tree>
          </template>
        </el-table-column>
        <el-table-column align="center" label="推送次数" prop="pushCount">
        </el-table-column>
        <el-table-column prop="updateBy" align="center" label="操作人">
        </el-table-column>
        <el-table-column align="center" min-width="150" label="操作">
          <template slot-scope="scope">
            <el-button type='text' v-hasPermi="['drillReport:query']" v-if="scope.row.pushCount > 0"
              @click="handleEdit(scope.row, '详情')">
              详情
            </el-button>
            <el-button type='text' v-hasPermi="['drillReport:edit']" v-else @click="handleEdit(scope.row, '编辑')">
              编辑
            </el-button>
            <!-- <el-button type='text' v-hasPermi="['drillReport:remove']" @click="handleDelete(scope.row)">
              删除
            </el-button> -->
            <el-button type='text' v-hasPermi="['drillReportPushTotalLog:add']" @click="handleEdit(scope.row, '推送')">推送
            </el-button>
            <el-button type='text' v-hasPermi="['drillReportPushTotalLog:query']" :disabled="scope.row.pushCount <= 0"
              @click="handleLog(scope.row)">
              记录</el-button>
         
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <el-dialog :title="title" :show-close="true" :close-on-click-modal="false" v-if="dialogVisible"
      :visible.sync="dialogVisible" width="50%">
      <template #title>
        <div style="display: flex;justify-content: space-between;color:#fff">
          <span>{{ title }}</span>
          <!-- <el-button v-if="title == '新增'"   size="mini" @click="history">历史事件模板
          </el-button> -->
        </div>
      </template>
      <div class="dialogBox">
        <div class="card-container">
          <el-row :gutter="10">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <!-- <el-col :span="24" :offset="0">
              <el-form-item label="信息类型" required prop="msgType">
                <el-radio-group v-model="form.msgType" :disabled="isTitle">
                  <el-radio v-for="dict in dict.type.sys_event_type" v-show="dict.label !== '正式'"
                    :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
              <el-col :span="20" :offset="0">
                <el-form-item label="震中地名" prop="locname">
                  <el-input v-model="form.locname" disabled>
                  </el-input>
                </el-form-item>

              </el-col>
              <el-col :span="4" :offset="0">
                <el-button  @click="getRandomChinaCoordinate" :disabled="isTitle">随机地址</el-button>
              </el-col>

              <el-col :span="12" :offset="0">
                <el-form-item label="震中经度(°)" prop="epilon">
                  <limit-input v-model="form.epilon" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="震中纬度(°)" prop="epilat">
                  <limit-input v-model="form.epilat" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="震级(M)" prop="magnitude">
                  <limit-input v-model="form.magnitude" :disabled="isTitle" :placeholder="'请输入震级'" />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="震源深度(km)" prop="focdepth">
                  <!-- <limit-input v-model="form.focdepth" :disabled="isTitle" :placeholder="'请输入深度'" /> -->
                  <el-input v-model="form.focdepth" :disabled="isTitle" oninput="value=value.replace(/[^0-9]/g,'')"
                    :placeholder="'请输入深度'">
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12" :offset="0">
              <el-form-item label="震中烈度(°)" prop="epiintensity">
                <el-input v-model="form.epiintensity" disabled>
                </el-input>
              </el-form-item>
            </el-col> -->

            </el-form>
          </el-row>
        </div>

        <div class="card-container">
          <div class="title">
            <div>信息接收对象 (已选 <span style="color:#409EFF;">{{ objectData.length }}</span> 个)</div>
            <el-button type='text' icon="el-icon-plus" :disabled="isTitle" @click="objectAdd">新增
            </el-button>
          </div>
          <div style="padding: 20px 20px;">
            <el-table :data="objectData" :height="maxHeight" style="width: 100%">
              <el-table-column prop="projectName" align="center" show-overflow-tooltip label="项目名称">
              </el-table-column>
              <el-table-column prop="siteName" align="center" show-overflow-tooltip label="站点名称">
              </el-table-column>
              <el-table-column prop="code" align="center" show-overflow-tooltip width="280" label="设备序列号">
              </el-table-column>
              <el-table-column prop="deviceType" align="center" show-overflow-tooltip label="设备类型">
                <template slot-scope="scope">
                  <dict-tag :options='dict.type.sys_device_mode' :value='scope.row.deviceType' />
                </template>
              </el-table-column>
              <el-table-column prop="onlineStatus" align="center" show-overflow-tooltip label="在线状态">
                <template slot-scope="scope">
                  <dict-tag :options='dict.type.sys_on_line_status' :value='scope.row.onlineStatus' />
                </template>
              </el-table-column>
              <el-table-column align="center" show-overflow-tooltip label="操作">
                <template slot-scope="scope">
                  <el-button type='text' :disabled="isTitle" @click="remove(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>


        <!-- <div class="title">
          <div>设置事件位置</div>
          <div>
            <el-popover placement="left" width="650" trigger="click">
              <el-table :data="gridData">
                <el-table-column type="index" align="center" label="序号" width="50">
                </el-table-column>
                <el-table-column width="150" align="center" property="intensity" label="本地预测烈度">
                </el-table-column>
                <el-table-column property="level" width="100" align="center" label="地震预警等级">
                </el-table-column>
                <el-table-column property="color" width="150" align="center" label="等级颜色">
                </el-table-column>
                <el-table-column min-width="200" align="center" property="text" label="避震指导">
                </el-table-column>
              </el-table>
              <el-button icon="el-icon-warning-outline"  size="mini" 
                slot="reference">预警规则说明</el-button>
            </el-popover>
          </div>
        </div> -->
        <!-- <div style="padding: 20px 20px;">
          <Map ref="map" :title="title" :topForm="form" :device="objectData"
            @getForm="updateLocation" />
        </div> -->

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlerCancel">取 消</el-button>
        <el-button  @click="handlerSubmit(null)" :disabled="objectData.length <= 0"
          v-if="!isTitle">仅保存</el-button>
        <el-button  v-hasPermi="['drillReportPushTotalLog:add']" :disabled="objectData.length <= 0"
          @click="handleSubmit" v-if="!isTitle">保存并推送</el-button>
        <el-button  @click="handlePush" v-if="title == '推送'">推送</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择接收对象" :close-on-click-modal="false" :visible.sync="objectVisible" width="50%">
      <div class="card-container">
        <el-row :gutter="20">
          <el-form :model="objectQuery" ref="objectQuery" :inline="true" label-width="80px">
            <el-col :span="20" :offset="0">
              <el-form-item label="序列号" prop="code">
                <el-input v-model="objectQuery.code" placeholder="请输入序列号" clearable
                  @keyup.enter.native="handleObjectQuery" />
              </el-form-item>
              <el-form-item label="项目名称" prop="shortName">
                <el-select v-model="objectQuery.shortName" clearable :style="'width:215px'" placeholder="请选择项目">
                  <el-option v-for="item in projectList" :key="item.projectId" :label="item.shortName"
                    :value="item.shortName">
                  </el-option>
                </el-select>
                <!-- <el-input v-model="objectQuery.shortName" placeholder="请输入项目名称" clearable
                @keyup.enter.native="handleObjectQuery" /> -->
              </el-form-item>
              <el-form-item label="设备类型" prop="deviceType">
                <el-select v-model="objectQuery.deviceType" clearable placeholder="请选择设备类型">
                  <el-option v-for="dict in this.dict.type.sys_device_mode" :key="dict.value" :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="在线状态" prop="onlineStatus">
                <el-select v-model="objectQuery.onlineStatus" clearable placeholder="请选择在线状态">
                  <el-option v-for="dict in dict.type.sys_on_line_status" :key="dict.value" :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设备型号" prop="modelId">
                <el-select v-model="objectQuery.modelId" clearable placeholder="请选择设备型号">
                  <el-option v-for="item in modList" :key="item.modelId" :label="item.model" :value="item.modelId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" :offset="0">
              <el-form-item>
                <el-button  icon="el-icon-search" size="mini" @click="handleObjectQuery">搜索
                </el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>

      <div class="card-container">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="预警终端" style="height: 401px;" name="receive">
            <el-table :data="receiveData" ref="receive" height="338" :row-key="getRowKeys" @selection-change="select"
              style="width: 100%">
              <el-table-column type="selection" align="center" :reserve-selection="true" width="55">
              </el-table-column>
              <el-table-column prop="projectName" align="center" show-overflow-tooltip label="项目名称">
              </el-table-column>
              <el-table-column prop="siteName" align="center" show-overflow-tooltip label="站点名称">
              </el-table-column>
              <el-table-column prop="code" align="center" show-overflow-tooltip label="设备序列号">
              </el-table-column>
              <el-table-column prop="modelId" align="center" show-overflow-tooltip label="设备型号">
                <template slot-scope="scope">
                  <span>{{ handleMode(scope.row.modelId) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deviceTypeLabel" align="center" show-overflow-tooltip label="设备类型">
                <!-- <template slot-scope="scope"> handleMode
                <dict-tag v-if="scope.row.type == 2" :options='dict.type.sys_publish_client_type'
                  :value='scope.row.clientType' />
                <dict-tag v-else :options='dict.type.sys_receive_client_type'
                  :value='scope.row.clientType' /> 
              </template> -->
              </el-table-column>
              <el-table-column prop="onlineStatus" align="center" show-overflow-tooltip label="在线状态">
                <template slot-scope="scope">
                  <dict-tag :options='dict.type.sys_on_line_status' :value='scope.row.onlineStatus' />
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="receiveTotal > 0" :total="receiveTotal" :page.sync="objectQuery.pageNum"
              :limit.sync="objectQuery.pageSize" @pagination="getObject" />
          </el-tab-pane>
        </el-tabs>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button  @click="handlerObjectSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 推送进度 -->
    <el-dialog :title="'推送进度'" :close-on-click-modal="false" :before-close="pushClose" v-if="pushScheduleOpen"
      :visible.sync="pushScheduleOpen" width="800px" append-to-body>
      <push-schedule @close="pushClose" :row="pushScheduleList" />
    </el-dialog>
    <!-- 推送记录 -->
    <el-dialog :title="'推送记录'" :close-on-click-modal="false" v-if="updateLogOpen" :visible.sync="updateLogOpen"
      width="800px" append-to-body>
      <update-log :row="updateList" @handleCheck="handleCheck" />
    </el-dialog>
    <!-- 升级失败设备列表 -->
    <el-dialog :title="failTitle" :close-on-click-modal="false" v-if="updateFailOpen" :visible.sync="updateFailOpen"
      width="1000px" append-to-body>
      <update-fail :row="updateFailList" />
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  handleAdd,
  getDetails,
  getDevice,
  getEewPushIndex,
  handleDelete,
  handleEdit,
  getCity,
  getLnglat,
} from '@/api/eewRehearsal/index.js';
import { getAddress } from '@/api/rehearsal/index.js';
import limitInput from '@/components/limitInput/index.vue';
import { getProject } from "@/api/runningLog/runningLog.js";
import pushSchedule from './pushSchedule.vue';
import updateLog from './updateLog.vue';
import updateFail from './updateFail.vue';
export default {
  name: 'eewRehearsal',
  dicts: [
    'earthquake_level',
    'sys_receive_client_type',
    'sys_publish_client_type',
    'sys_push_state',
    'sys_event_type',
    'sys_on_line_status',
    'sys_device_mode',
  ],
  components: {
    limitInput,
    pushSchedule,
    updateLog,
    updateFail,
  },
  data() {
    const _this = this;
    return {
      citylist: [],
      msgId: [],
      updateFailOpen: false,
      failTitle: '速报演练推送失败设备列表',
      updateFailList: {},
      updateList: {},
      updateLogOpen: false,
      pushScheduleList: {
        row: {},
        drillPushTotalId: null,
      },
      pushScheduleOpen: false,
      gridData: [
        {
          intensity: '小于3度',
          level: '无预警',
          color: '无预警（紫色）',
          text: '此次地震无影响',
        },
        {
          intensity: '大于等于3度小于4度',
          level: 'Ⅳ级',
          color: '蓝色预警',
          text: '有感地震，注意观察',
        },
        {
          intensity: '大于等于4度小于6度',
          level: 'Ⅲ级',
          color: '黄色预警',
          text: '有感地震，注意防范',
        },
        {
          intensity: '大于等于6度小于8度',
          level: 'Ⅱ级',
          color: '橙色预警',
          text: '强烈地震，立即避险',
        },
        {
          intensity: '大于等于8度',
          level: 'Ⅰ级',
          color: '红色预警',
          text: '破坏地震，紧急避险',
        },
      ],
      multiple: true,
      times: null,
      modList: [],
      projectList: [],
      publishData: [],
      publishTotal: 0,
      receiveTotal: 0,
      receiveData: [],
      options: [],
      activeName: 'receive',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locname: null,
        createTime: [],
        msgType: '0',
      },
      form: {
        address: null,
        epilon: null,
        epilat: null,
        locname: null,
        deviceId: [],
        msgType: '',
        addressList: [],
        epiintensity: 0,
        magnitude: '8',
        focdepth: '20',
      },
      tableData: [],
      total: 0,
      date: [],
      title: '',
      dialogVisible: false,
      objectVisible: false,
      rules: {
        addressList: [
          { required: true, message: '震中地名不能为空', trigger: 'change' },
        ],
        magnitude: [
          { required: true, message: '震级不能为空', trigger: 'blur' },
        ],
        oritimes: [
          { required: true, message: '发震时间不能为空', trigger: 'change' },
        ],
        focdepth: [
          { required: true, message: '深度不能为空', trigger: 'blur' },
        ],
        locname: [
          { required: true, message: '震中地名不能为空', trigger: 'blur' },
        ],
        epilon: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
        epilat: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
        sendTime: [
          {
            required: true,
            message: '演练发布时间不能为空',
            trigger: 'change',
          },
        ],
      },
      objectQuery: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        shortName: null,
        deviceType: null,
        onlineStatus: null,
        modelId: null
      },
      isPromptly: false,
      oritimes: null,
      objectData: [],
      publishIds: [],
      receiveIds: [],
      addressName: [],
    };
  },
  computed: {},
  created() {
    // if (process.client){}
  },
  mounted() {
    this.getList();
    this.queryCity();
    this.getConfig()
  },
  computed: {
    isTitle() {
      if (this.title == '新增' || this.title == '编辑') {
        return false;
      } else {
        return true;
      }
    },
    maxHeight() {
      // if (this.objectData.length > 4) {
      //   return '300';
      // } else if (this.objectData.length >= 2 && this.objectData.length < 4) {
      //   return '200';
      // } else {
      //   return '100';
      // }
      return '300';
    },
  },
  watch: {
    activeName(val) {
      this.$nextTick(() => {
        this.$refs[val].doLayout();
      });
    },
    objectVisible() {
      this.activeName = 'receive';
    },
    'form.magnitude'() {
      if (this.form.magnitude > 12) {
        this.form.magnitude = 12;
      } else if (this.form.magnitude < 0) {
        this.form.magnitude = 0;
      }
      if (this.form.magnitude <= 1.5) {
        this.form.epiintensity = 0;
      } else {
        this.form.epiintensity = Math.floor((this.form.magnitude - 1.5) / 0.58);
      }
    },
  },
  beforeCreate() { },
  beforeMount() { },
  beforeDestroy() { },
  methods: {
    getRowKeys(row) {
      return row.deviceId;
    },
    queryCity() {
      getCity().then((response) => {
        this.citylist = response.data;
      });
    },
    // 随机生成中国经纬度
    getRandomChinaCoordinate() {
      // 中国经度范围
      var minLng = 90;
      var maxLng = 120;
      // 中国纬度范围
      var minLat = 15;
      var maxLat = 50;

      // 生成随机经度
      var longitude = (Math.random() * (maxLng - minLng) + minLng).toFixed(6);
      // 生成随机纬度
      var latitude = (Math.random() * (maxLat - minLat) + minLat).toFixed(6);

      this.form.epilon = longitude
      this.form.epilat = latitude
      this.getAddress(longitude, latitude)
    },
    async getAddress(lon, lat) {
      const res = await getAddress(lon, lat)
      if (res.code == 200) {
        if (res.msg == '' || res.msg == null) {
          return this.getRandomChinaCoordinate()
        }
        this.$set(this.form, 'locname', res.msg)
      }
    },
    // 省市区联动变化后
    handleAddress(val) {
      if (val.length > 0) {
        let addressName = [];
        this.citylist.forEach((item1) => {
          if (item1.code == val[0]) {
            addressName.push(item1.name);
            item1.child.forEach((item2) => {
              if (item2.code == val[1]) {
                addressName.push(item2.name);
                item2.child.forEach((item3) => {
                  if (item3.code == val[2]) {
                    addressName.push(item3.name);
                  }
                });
              }
            });
          }
        });
        console.log(val, addressName);
        this.addressName = addressName;
        getLnglat({
          adCode: val[2],
          city: addressName[1],
          area: addressName[2],
        }).then((response) => {
          if (Object.keys(response.data).length > 0) {
            this.form.epilon = response.data.longitude;
            this.form.epilat = response.data.latitude;
          }
        });
      }
    },
    pushClose() {
      this.pushScheduleOpen = false;
      this.handleQuery();
    },
    async handleDelete() {
      this.$modal.confirm('是否确认删除？').then(async () => {
        const res = await handleDelete(this.msgId);
        if (res.code == 200) {
          this.$modal.msgSuccess(res.msg);
          this.handleQuery();
        }
      });
    },
    handleLog(row) {
      this.updateList = row;
      this.updateLogOpen = true;
    },
    handleCheck(row, sta) {
      this.updateFailList = row;
      if (sta == '0') {
        this.updateFailList.pushStatus = sta;
        this.failTitle = '速报演练推送失败设备列表';
      } else {
        this.updateFailList.pushStatus = '';
        this.failTitle = '速报演练推送设备列表';
      }
      this.updateFailOpen = true;
    },
    mend(val) {
      if (val < 10) {
        return '0' + val;
      } else {
        return val;
      }
    },
    initTime(time) {
      let date = new Date(time);
      let Y = date.getFullYear() + '-';
      let M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-';
      let D = date.getDate() + ' ';
      let h = date.getHours() + ':';
      let m = date.getMinutes() + ':';
      let s = date.getSeconds();
      return h + m + s;
    },
    select(row) {
      if (this.activeName == 'publish') {
        this.publishIds = row;
      } else {
        this.receiveIds = row;
      }
    },
    remove(row) {
      this.objectData = this.objectData.filter((item) => {
        return item.deviceId !== row.deviceId;
      });
    },
    // updateLocation(Addr) {
    //   if (this.title !== '查看') {
    //     // this.form.epilon = Addr.lon;
    //     // this.form.epilat = Addr.lat;
    //     // this.form.locname = Addr.orgAddr;
    //     this.form.epilon = Addr.longitude;
    //     this.form.epilat = Addr.latitude;
    //     // this.form.locname = Addr.address;
    //     this.form.addressList = Addr.addressList;
    //     // this.form.addressName = Addr.addressName;
    //     console.log(Addr);
    //     this.form.locname = Addr.addressName;
    //     console.log(this.form);
    //   }
    // },
    spot() {
      if (!this.isTitle) {
        this.$refs.map.mapDraw([this.form.epilon, this.form.epilat]);
      }
    },
    getRowKey(row) {
      return row.msgId;
    },
    handleSelectionChange(selection) {
      this.msgId = selection.map((item) => item.msgId);
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.form = {
        epilon: null,
        epilat: null,
        locname: null,
        deviceId: [],
        msgType: '',
        epiintensity: 0,
        magnitude: '8',
        focdepth: '20',
        addressList: [],
      };
      this.title = '新增';
      this.isPromptly = false;
      this.objectData = [];
      this.dialogVisible = true;
    },
    async handleEdit(row, title) {
      this.times && clearTimeout(this.times);
      const res = await getDetails(row.msgId);
      if (res.code == 200) {
        this.title = title;
        // this.form = Object.assign(this.form, res.data);
        this.form = res.data;
        this.form.addressList = res.data.address.split(',');
        console.log('this.form.addressList', this.form.addressList);
        this.objectData = res.data.deviceInfo;
        this.dialogVisible = true;
        // this.$nextTick(() => {
        //   this.times = setTimeout(() => {
        //     this.$refs.map.handlePosition(true);
        //   }, 800);
        // });
      }
    },
    async objectAdd() {
      this.objectQuery = {
        pageNum: 1,
        pageSize: 10,
        code: null,
        shortName: null,
        deviceType: null,
        onlineStatus: null,
        modelId: null
      };
      // this.publishData = [];
      this.receiveData = [];
      // const project = await this.$api.getProject();
      // if (project.code == 200) {
      //   this.options = project.data;
      // }
      this.getObject();
      this.objectVisible = true;
      this.$nextTick(() => {
        this.$refs.receive.clearSelection();
        this.objectData.forEach((item) => {
          this.$refs.receive.toggleRowSelection(item, true);
        });
      });
    },
    async getObject() {
      const res1 = await getDevice(this.objectQuery);
      if (res1.code == 200) {
        this.receiveData = res1.rows;
        this.receiveTotal = res1.total;
        if (this.objectData.length > 0) {
          let data = this.objectData.map((item) => {
            return item.deviceId;
          });

          this.receiveData.forEach((item) => {
            if (data.includes(item.deviceId)) {
              this.$nextTick(() => {
                this.$refs['receive'].toggleRowSelection(item, true);
              });
            }
          });
          // this.$refs['publish'].toggleRowSelection(item, true);
        }
      }
    },
    async getList() {
      const res = await getList(this.queryParams);
      if (res.code == 200) {
        this.tableData = res.rows;
        this.total = res.total;
      }
    },
    async getConfig() {
      this.modList = await this.$api.getMod();
      const res = await getProject();
      if (res.code == 200) {
        this.projectList = res.data;
      }
    },
    handleMode(type) {
      const facId = this.modList.filter((item) => {
        return item.modelId == type;
      })[0].model;
      return facId
    },
    handleObjectQuery() {
      this.getObject();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.queryParams.level = [this.level, this.level1];
      this.getList();
    },
    resetQuery() {
      this.resetForm('queryForm');
      this.date = [];
      this.handleQuery();
    },
    handleRouter(row) {
      this.$router.push({
        path: 'transpondDetails',
        query: { msgId: row.msgId },
      });
    },
    getRowClass(row, rowIndex) {
      // console.log(row);
      if (row.row.normalWarnings) {
        if (row.row.normalWarnings.length === 0) {
          return 'row-expand-cover';
        }
      } else {
        return 'row-expand-cover';
      }
    },
    handlerObjectSubmit() {
      this.objectData = [];
      if (this.objectData.length > 0) {
        const data = this.publishIds.concat(this.receiveIds);
        this.objectData = this.objectData.concat(data);
      } else {
        this.objectData = this.publishIds.concat(this.receiveIds);
      }
      console.log(this.objectData);
      this.objectVisible = false;
    },
    async handlerSubmit(cb) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.form.deviceId = this.objectData.map((item) => {
            return item.deviceId;
          });
          // this.form.address = this.form.addressList.join();
          // this.form.locname = this.addressName.join().replace(/,/g, '');
          if (this.form.msgId == null) {
            const res = await handleAdd(this.form);
            if (res.code == 200) {
              this.$modal.msgSuccess(res.msg);
              this.dialogVisible = false;
              this.handleQuery();
              cb && cb(res);
            } else {
              this.$modal.msgError(res.msg);
            }
          } else {
            const res = await handleEdit(this.form);
            if (res.code == 200) {
              this.$modal.msgSuccess(res.msg);
              this.dialogVisible = false;
              this.handleQuery();
              cb && cb(res);
            } else {
              this.$modal.msgError(res.msg);
            }
          }
        }
      });
    },
    async handleSubmit() {
      this.handlerSubmit((res) => {
        this.handlePush(res.data);
      });
    },
    async handlePush(row) {
      if (this.title == '推送') {
        const res = await getEewPushIndex({ msgId: this.form.msgId });
        if (res.code == 200) {
          this.pushScheduleList = {
            row: this.form,
            drillPushTotalId: res.data,
          };
          this.dialogVisible = false;
          this.pushScheduleOpen = true;
        }
      } else {
        const res = await getEewPushIndex({ msgId: row.msgId });
        if (res.code == 200) {
          this.pushScheduleList = {
            row,
            drillPushTotalId: res.data,
          };
          this.pushScheduleOpen = true;
        }
      }
    },
    handlerCancel() {
      this.dialogVisible = false;
    },
    history() {
      this.$router.push({
        path: '/message/eventQuery',
      });
    },
  },
};
</script>
<style lang='scss' scoped>
.box {
  width: 100%;
  height: 100%;
  padding: 20px;
}
.body-title {
  display: flex;
  position: relative;
  // justify-content: space-between;
  align-items: center;
}

.body-title-left {
  height: 100%;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: #fff;
  line-height: 64px;
}

.body-title-right {
  position: absolute;
  right: 0;
}

.eewMessage {
  >div {
    display: flex;
    text-align: left;
  }
}

.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 20px 0 20px;
  font-weight: 700;
  font-size: 16px;
  color: #fff;
}

.dialogBox {
  height: 648px;
  padding: 0 12px;
  overflow: hidden;
  overflow-y: auto;
}

::v-deep .el-tree-node__content:hover,
.el-upload-list__item:hover {
  background: rgba(255, 255, 255, 0.3);
  color: #0095ff;
}

::v-deep .el-tree-node:focus>.el-tree-node__content {
  background: rgba(0, 149, 255, 0.1);
}
</style>